<?php

namespace App\Http\Controllers\Api;

use App\ActiveParty;
use App\ActivePartyBanner;
use App\Activity;
use App\ActivityBindGoods;
use App\ActivityBrowseRecord;
use App\ActivityImg;
use App\ActivityJoin;
use App\Classify;
use App\CommentLike;
use App\Files;
use App\Goods;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\IntegralChildRule;
use App\IntegralRule;
use App\InvitationCard;
use App\JoinActivity;
use App\User;
use App\UserActivity;
use App\UserAttentionActivity;
use App\UserCollection;
use App\UserIntegralRecord;
use App\VipInfo;
use Intervention\Image\Facades\Image;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;

class activityController extends Controller
{
    /**
     *获取活动分类
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityClassify(Request $request){

        /** @var Classify $classify */
        $classifies=Classify::wherePid(0)->whereType('activity')->orderBy('sort','asc')->orderBy('created_at','desc')->get();
        if(count($classifies)>0){
            foreach($classifies as $classify){
                $classifyChild = Classify::wherePid($classify->id)->whereType('activity')->count();
                if($classifyChild > 0){
                    $classify->has_secondary = 1;
                }else{
                    $classify->has_secondary = 0;
                }

                /** @var Classify $classifyChild */
                $classifyChildList = Classify::wherePid($classify->id)->whereType('activity')->get();
                $classify->child_classify_list = $classifyChildList;
            }
        }

        return response()->json(["level"=>"success","message"=>"获取成功！","data"=>$classifies]);
    }

    /**
     * 获取活动列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivity(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        $keywords      = $request->get('keywords');
        $activePartyId = !is_null($request->get('active_party_id')) ? $request->get('active_party_id') : 0;
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        if($user == false){
            $user = null;
        }

        $page = $page - 1;
        $activities = CommonManager::getActivityList('list',$limit,$page,$keywords,'',$activePartyId,0,1,$user);
        $pageInfo['total'] = CommonManager::getActivityNum($keywords,$activePartyId,0,1);

        return response()->json(["level"=>"success","message" => "获取成功！","data" => $activities,'page_info' => $pageInfo]);
    }

    /**
     * 获取活动详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getActivityDetail(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        if($user){
            CommonManager::activityBrowseRecord($activityId,$user->id,$request->ip());
        }else{
            CommonManager::activityBrowseRecord($activityId,0,$request->ip());
        }

        if($user == false){
            $user = null;
        }
        $activity = Activity::whereId($activityId)->withTrashed()->first();
        if ($activity && $activity->deleted_at!=null){
            if($user){
                $userAttackActivity = UserAttentionActivity::whereActivityId($activity->id)->whereUserId($user->id)->first();
                if($userAttackActivity){
                    return response()->json(['level'=>'error','message'=>'该活动已被删除','data' => 1]);
                }else{
                    return response()->json(['level'=>'error','message'=>'该活动已被删除','data' => 2]);
                }
            }else{
                return response()->json(['level'=>'error','message'=>'该活动已被删除','data' => '']);
            }
        }

        $activityDetail = CommonManager::getActivityList('detail',0,0,'','',0,0,1,$user,$activityId);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $activityDetail]);
    }

    /**
     * 获取分享二维码图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\WechatException
     */
    public function generateShareQrCode(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动已下架']);

        if($thisActivity->share_img_id != 0){
            $url = FileManager::getImgUrl($thisActivity->share_img_id);
            return response()->json(['level' => 'success','message' => '获取成功','data' => $url]);
        }

        if($thisActivity->qr_code_img_id == 0){
            $scene = "id=".$thisActivity->id;
            $path  = 'pages/detail/main?'.$scene;

            //生成微信小程序的二维码图片
            $wxAppQrCodeContent = WechatLogin::getWxUnlimitQrcodeByToken($path);
            if($wxAppQrCodeContent){
                $filoInfo = FileManager::saveFileByFileContent($wxAppQrCodeContent,"qr_code_" . $thisActivity->id . ".jpg","");
                $newImage = new Images();
                $newImage->file_id          = $filoInfo->id;
                $newImage->img_name         = "qr_code_" . $thisActivity->id . ".jpg";
                $newImage->img_type         = $filoInfo->file_type;
                $newImage->save();

                $thisActivity->qr_code_img_id = $newImage->id;
                $thisActivity->save();
            }else{
                return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
            }
        }else{
            /** @var Images $qrCodeImg */
            $qrCodeImg = Images::whereId($thisActivity->qr_code_img_id)->first();
            if(!$qrCodeImg)
                return false;

            /** @var Files $qrCodeFile */
            $qrCodeFile = Files::whereId($qrCodeImg->file_id)->first();
            if(!$qrCodeFile)
                return false;

            $wxAppQrCodeContent = $qrCodeFile->getContent();
        }

        //背景图片
        $backgroundImgInfo = Image::make(url('images/fenxiang.png'));

        //二维吗图片
        $wxAppQrCodeImgInfo = Image::make($wxAppQrCodeContent);

        //设置二维吗图片的的大小
        $wxAppQrCodeImgInfo->resize(250,250);
        //调整二维吗在背景图片上的位置
        $backgroundImgInfo->insert($wxAppQrCodeImgInfo,'top-left',175,380);

        if($thisActivity->img_id != 0){
            /** @var Images $thisImg */
            $thisImg = Images::whereId($thisActivity->img_id)->first();
            if(!$thisImg)
                $activityImgContent = url('images/default_img.png');

            /** @var Files $thisFile */
            $thisFile = Files::whereId($thisImg->file_id)->first();
            if(!$thisFile)
                $activityImgContent = url('images/default_img.png');

            $activityImgContent = $thisFile->getContent();
        }else{
            $activityImgContent = url('images/default_img.png');
        }

        //活动图片
        $activityImgInfo = Image::make($activityImgContent)->resize(520,320);;

        //调整活动图片在背景图片上的位置
        $backgroundImgInfo->insert($activityImgInfo,'top-left',40,20);

        //拼写地址信息
        $activityAddressInfo = mb_strimwidth($thisActivity->province . $thisActivity->city . $thisActivity->area . $thisActivity->address_detail,0,44,'...','utf-8');

        //调整地址信息在图片上的位置
        $backgroundImgInfo->text($activityAddressInfo,300, 700, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(14);
            $font->color('#000000');//5a5a5a
            $font->align('center');
            $font->valign('top');
            $font->angle(0);
        });

        //活动主题
        $activityThemeInfo = mb_strimwidth($thisActivity->theme,0,20,'...','utf-8');

        //调整活动主题在图片上的位置
        $backgroundImgInfo->text($activityThemeInfo, 300, 670, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(18);
            $font->color('#000000');//5a5a5a
            $font->align('center');
            $font->valign('top');
            $font->angle(0);
        });

        //活动时间
        $activityTimeInfo = $thisActivity->start_time;

        //调整活动时间在图片上的位置
        $backgroundImgInfo->text($activityTimeInfo, 300, 730, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(14);
            $font->color('#000000');//5a5a5a
            $font->align('center');
            $font->valign('top');
            $font->angle(0);
        });

        //输出图片
        $response = response()->make($backgroundImgInfo->encode('jpg'));
        $response->header('Content-Type', 'image/jpg');

        return $response;
    }

    /**
     * 活动浏览量记录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityBrowseRecord(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        /** @var Activity $activity */
        $activity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$activity)
            return response()->json(['level' => 'error','message' => '该活动不存在']);

        /** @var ActivityBrowseRecord $thisActivityBrowseRecord */
        $thisActivityBrowseRecord = ActivityBrowseRecord::whereActivityId($activity->id)->whereUserId($user->id)->orderBy('created_at','desc')->first();
        if($thisActivityBrowseRecord){
            if(strtotime($thisActivityBrowseRecord->created_at) + 300 <= time()){
                $newActivityBrowseRecord = new ActivityBrowseRecord();
                $newActivityBrowseRecord->user_id       = $user->id;
                $newActivityBrowseRecord->activity_id   = $activity->id;
                $newActivityBrowseRecord->save();

                $activity->browse_num += 1;
                $activity->save();
            }
        }else{
            $newActivityBrowseRecord = new ActivityBrowseRecord();
            $newActivityBrowseRecord->user_id       = $user->id;
            $newActivityBrowseRecord->activity_id   = $activity->id;
            $newActivityBrowseRecord->save();

            $activity->browse_num += 1;
            $activity->save();
        }

        return response()->json(['level' => 'success','message' => '记录成功','data' => $thisActivityBrowseRecord]);
    }

    /**
     * 用户关注活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userAttentionActivity(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        /** @var Activity $activity */
        $activity = DB::table('activity')->whereId($activityId)->first();
        if(!$activity)
            return response()->json(['level' => 'error','message' => '该活动不存在']);

        $userAttentionActivity = UserAttentionActivity::whereUserId($user->id)->whereActivityId($activity->id)->first();
        if($userAttentionActivity){
            $userAttentionActivity->forceDelete();
            $attention_num = $activity->attention_num - 1;

            \Illuminate\Support\Facades\DB::table('activity')->where('id',$activityId)->update(['attention_num' => $attention_num]);

            return response()->json(['level' => 'error','message' => '取消成功']);
        }

        $newUserAttentionActivity = new UserAttentionActivity();
        $newUserAttentionActivity->user_id          = $user->id;
        $newUserAttentionActivity->activity_id      = $activity->id;
        $newUserAttentionActivity->save();

        $activity->attention_num += 1;
        $activity->save();

        return response()->json(['level' => 'success','message' => '关注成功','data' => $newUserAttentionActivity]);
    }

    /**
     * 获取活动状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityCheckStatus(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'login']);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动不存在']);

        if(strtotime($thisActivity->end_time) <= time())
            return response()->json(['level' => 'error','message' => '活动已结束']);

        /** @var ActivityJoin $userActivity */
        $userActivity = ActivityJoin::whereUserId($user->id)->whereActivityId($thisActivity->id)->whereStatus(1)->first();
        if(!$userActivity)
            return response()->json(['level' => 'success','message' => '您还没有参与该活动','data' => 0]);

        if($userActivity->is_sign == 1){
            $status = 1;
        }else{
            $status = 0;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $status]);
    }

    /**
     * 活动签到接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function activityCheckIn(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $activityId = !is_null($request->get('activity_id')) ? $request->get('activity_id') : 0;

        /** @var Activity $thisActivity */
        $thisActivity = Activity::whereId($activityId)->whereStatus(1)->first();
        if(!$thisActivity)
            return response()->json(['level' => 'error','message' => '活动不存在']);

        if(strtotime($thisActivity->end_time) <= time())
            return response()->json(['level' => 'error','message' => '活动已结束']);

        /** @var ActivityJoin $userActivity */
        $userActivity = ActivityJoin::whereUserId($user->id)->whereActivityId($thisActivity->id)->whereStatus(1)->first();
        if(!$userActivity)
            return response()->json(['level' => 'error','message' => '您还没有参与该活动']);

        if(strtotime($thisActivity->start_time) > time())
            return response()->json(['level' => 'error','message' => '活动还未开始']);

        if($userActivity->is_sign == 1)
            return response()->json(['level' => 'error','message' => '您已经签到过了']);

        $userActivity->is_sign = 1;
        $userActivity->save();

        return response()->json(['level' => 'success','message' => '签到成功','data' => $userActivity]);
    }

//    /**
//     * 获取活动方列表
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function getActivePartyList(Request $request){
//        $type = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'default';
//        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
//        $page = !is_null($request->get('page')) ? $request->get('page') : 0;
//
//        /** @var ActiveParty $activeParty */
//        if($type == 'default'){
//            $activePartyList = ActiveParty::whereStatus(1)->orderBy('popularity','desc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
//        }elseif($type == 'popularity'){
//            $activePartyList = ActiveParty::whereStatus(1)->orderBy('popularity','desc')->orderBy('created_at','desc')->take(4)->get();
//        }else{
//            $activePartyList = ActiveParty::whereStatus(1)->orderBy('popularity','desc')->orderBy('created_at','desc')->offset($limit * $page)->limit($limit)->get();
//        }
//
//        if(count($activePartyList) > 0){
//            foreach($activePartyList as $activeParty){
//                $activeParty->thumb_url = FileManager::getImgUrl($activeParty->thumb_id);
//            }
//        }
//
//        return response()->json(['level' => 'success','message' => '获取成功','data' => $activePartyList]);
//    }
//
//    /**
//     * 获取活动方详情
//     * @param Request $request
//     * @return \Illuminate\Http\JsonResponse
//     */
//    public function getActivePartyDetail(Request $request){
//        $activePartyId = !is_null($request->get('active_party_id')) ? $request->get('active_party_id') : 0;
//
//        /** @var ActiveParty $activePartyDetail */
//        $activePartyDetail = ActiveParty::whereId($activePartyId)->whereStatus(1)->first();
//        if($activePartyDetail){
//            $activePartyDetail->logo_url               = FileManager::getImgUrl($activePartyDetail->logo_id);
//            $activePartyDetail->site_present_video_url = FileManager::getVideoUrl($activePartyDetail->site_present_video_id);
//        }
//
//        return response()->json(['level' => 'success','message' => '获取成功','data' => $activePartyDetail]);
//    }
}
